<?php
/**
 * Country
 * Класс Country отвечает за обработку стран
 * @author Sayp
 */
class Country extends ActiveRecord {
	protected static $_tableName = 'country';
	protected static $_pkName = 'ID_country';
	
	protected static $_essenceType = 2;
	
	protected function afterValidation() {
		$objDB = Service_Database::instance();
		$stmt = "SELECT `ID_country` FROM `country` WHERE `country_url` = '" . $this->getField('country_url') . "'";
		if ($this->id) $stmt .= ' AND `ID_country` != ' . $this->id;
		if ($objDB->isRecordExist($stmt)) $this->arrErrors = 'Такой url уже используется';
	}
	
	public static function updateMinPrices() {
		$objDB = Service_Database::instance();
		$objDB->query('UPDATE `country` SET `price_min` = NULL WHERE `ID_lvl_country` IS NOT NULL');
		
		// lvl prices
		$objLvlApi = new Lvl_Api();
		
		$arrLvlCountryIds = $objDB->selectSimpleArray('
			SELECT `iso`
			FROM `country`
			WHERE `ID_lvl_country` IS NOT NULL
		');
		
		foreach ($arrLvlCountryIds as $iso) {
			$minPrice = $objLvlApi->getCountryPrice($iso);
			if ($minPrice) $objDB->query("UPDATE `country` SET `price_min` = " . $minPrice . " WHERE `iso` = '" . $iso . "'"); 			
		}
	}
	
	public function getWeather() {
		if (!$this->id) return array();
		
		$objDB = Service_Database::instance();
		
		return $objDB->select('
			SELECT round(AVG(`daily_temp`)) as `temp`, MONTH(`date`) as `month`
			FROM `weather`
			INNER JOIN `resort` USING(`ID_resort`)
			WHERE `ID_country` = ' . $this->id . '
			GROUP BY `month`
			ORDER BY `month`
		');
	}
	
	public function getWeatherCountryResort() {
		if (!$this->id) return array();
		
		$objDB = Service_Database::instance();
		return Service_ArrayConverter::groupArray($objDB->select('
			SELECT `ID_resort`, round(AVG(`daily_temp`)) as `temp`, MONTH(`date`) as `month`
			FROM `weather`
			INNER JOIN `resort` USING(`ID_resort`)
			WHERE `ID_country` = ' . $this->id . '
			GROUP BY `ID_resort`, `month`
			ORDER BY `ID_resort`, `month`
		'), 'ID_resort');
		
	}
	
	public function getResorts($limit = 4) {
		if (!$this->id) return array();
	
		$objResort = new Resort();
		
		return $objResort->find('all', array(
			'conditions' => '`ID_country` = ' . $this->id,
		));
	}
}